/*
 * @Author: 彭林
 * @Date: 2021-05-12 16:56:31
 * @LastEditTime: 2021-07-14 18:28:50
 * @LastEditors: 彭林
 * @Description:
 * @FilePath: /saas-app/app/service/user_token.go
 */
package service

import (
	"database/sql"
	"saas-app/app/dao"
	"saas-app/app/model"
)

type UserTokenRepository interface {
	GetUserTokenByUserId(userid uint) *model.UserToken
	SaveToken(userToken *model.UserToken) (sql.Result, error)
	Vtoken(userId uint, token string) bool
}

type userToken struct{}

func UserTokenService() UserTokenRepository {
	return &userToken{}
}

func (u userToken) GetUserTokenByUserId(userid uint) *model.UserToken {
	record, _ := dao.UserToken.FindOne("user_id = ?", userid)
	user := &model.UserToken{}
	record.Struct(&user)
	return user
}

func (u userToken) SaveToken(userToken *model.UserToken) (sql.Result, error) {
	r, err := dao.UserToken.Save(userToken)
	return r, err
}

func (u userToken) Vtoken(userId uint, token string) bool {
	userToken := UserTokenService().GetUserTokenByUserId(userId)
	if userToken == nil {
		return false
	}
	return userToken.Token == token
}
